<template>
  <!-- 1. 卡片背景 -->
  <el-card class="box-card">
    <!-- 加：添加按钮 -->
    <el-button type="primary" icon="Plus" class="addMark" @click="addTrades">
      添加品牌
    </el-button>
    <!-- 表格 -->
    <el-table
      :data="tradeData.value"
      class="tradeTable"
      border
      style="width: 100%"
    >
      <el-table-column
        label="序号"
        width="100"
        type="index"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="tmName"
        label="品牌名称"
        width="200"
      ></el-table-column>
      <el-table-column label="品牌LOGO" width="200">
        <template #="{ row, $index }">
          <img :src="row.logoUrl" style="width: 50px; height: 50px" />
        </template>
      </el-table-column>
      <el-table-column label="品牌操作">
        <template #="{ row, $index }">
          <el-button
            type="primary"
            size="small"
            icon="Edit"
            @click="updateTrades(row)"
          ></el-button>
          <!-- <el-popover placement="top" width="160" v-model="visiblePop">
            <p>确定删除 {{ row.tmName }} 吗？</p>
            <div style="text-align: right; margin: 0">
              <el-button size="small" @click="visiblePop = false">取消</el-button>
              <el-button type="primary" size="small" @click="confirmDelete(row.id)">确定</el-button>
            </div>
              <el-button slot="reference" type="primary" icon="Delete" @click="visiblePop = true"></el-button>
          </el-popover> -->
          <!-- <el-button slot="reference">删除</el-button> -->
          <el-popconfirm
            :title="`您确定要删除${row.tmName}?`"
            width="250px"
            icon="Delete"
            @confirm="removeTradeMark(row.id)"
          >
            <template #reference>
              <el-button type="primary" size="small" icon="Delete"></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :background="true"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      v-model:current-page="currentPage"
      :page-sizes="[3, 5, 7, 9]"
      v-model:page-size="curLimit"
      layout="prev, pager, next, jumper,->,sizes,total"
      :total="totalData"
    ></el-pagination>
  </el-card>
  <!-- :visible.sync="centerDialogVisible"   示例写法为啥是错的-->
  <el-dialog
    :title="addTradesParames.id ? '修改品牌' : '添加品牌'"
    v-model="dialogVisible"
    width="50%"
  >
    <el-form
      label-width="80px"
      :rules="rules"
      :model="addTradesParames"
      ref="tradeForm"
    >
      <el-form-item label="品牌名称" prop="tmName">
        <el-input
          type="text"
          v-model="addTradesParames.tmName"
          placeholder="请输入品牌名称"
          style="width: 280px"
        ></el-input>
      </el-form-item>
      <el-form-item label="品牌LOGO" prop="logoUrl">
        <el-upload
          class="avatar-uploader"
          action="/api/admin/product/fileUpload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img
            v-if="addTradesParames.logoUrl"
            :src="addTradesParames.logoUrl"
            class="avatar"
          />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleTardesmark">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import {
  reqTrademark,
  reqAddOrUpdateTrades,
  reqDeleteTrade,
} from '../../../api/product/trademark'
import {
  TrademarksResponse,
  Records,
  Trades,
} from '../../../api/product/trademark/type'
import { ElMessage, formEmits } from 'element-plus'
let dialogVisible = ref<boolean>(false)
// let visiblePop = ref<boolean>(true)
let currentPage = ref<number>(1)
let curLimit = ref<number>(3)
// tradeData 数据在 模板中使用时需要带 .value
let tradeData = reactive<Records>([])
let addTradesParames = reactive<Trades>({
  tmName: '',
  logoUrl: null,
})
let totalData = ref<number>(0)
let getTrademark = async (page = 1) => {
  currentPage.value = page
  console.log(curLimit.value)
  let res: TrademarksResponse = await reqTrademark(page, curLimit.value)
  console.log(899, res)
  if (res.code === 200) {
    tradeData.value = res.data.records
    totalData.value = res.data.total
    console.log(tradeData.value, totalData.value)
  }
}

let removeTradeMark = async (id: number) => {
  // console.log(1234567,tradeData.value.length);
  let page =
    tradeData.value.length > 1 ? currentPage.value : currentPage.value - 1
  let res = await reqDeleteTrade(id)
  console.log(23333, res)
  getTrademark(page)
}

let validateTmName = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入品牌名称'))
  } else if (value.trim().length < 2) {
    // trim()方法用于去除字符串两端的空白字符，包括空格、制表符和换行符。
    callback(new Error('品牌名称长度不能小于 2 位'))
  } else {
    callback()
  }
}

let validateLogoUrl = (rule, value, callback) => {
  console.log(111111)
  if (!value) {
    callback(new Error('请上传 logo 图片'))
  } else {
    callback()
  }
}
let tradeForm = ref()
let rules = {
  tmName: [{ required: true, validator: validateTmName, trigger: 'blur' }],
  // 此处文件上传无法单独定义触发校验方式
  logoUrl: [{ required: true, validator: validateLogoUrl, trigger: 'blur' }],
}
let updateTrades = (row: any) => {
  dialogVisible.value = true
  console.log(row)
  //   addTradesParames.id = row.id
  //   addTradesParames.tmName = row.tmName
  //   addTradesParames.logoUrl = row.logoUrl
  // 以上部分等同于  浅拷贝
  Object.assign(addTrades, row)
}

let handleTardesmark = async () => {
  await tradeForm.value.validate()
  // console.log('1314',result);

  let res: any = await reqAddOrUpdateTrades(addTradesParames)
  if (res.code === 200) {
    console.log(currentPage.value)
    // 此处个人觉得无论添加还是修改  都留在当前页比较好  就没跟老师一致
    await getTrademark(currentPage.value)
    ElMessage({
      type: 'success',
      message: addTradesParames.id ? '修改成功' : '添加成功',
    })
    dialogVisible.value = false
  } else {
    ElMessage({
      type: 'error',
      message: '操作失败',
    })
    dialogVisible.value = false
  }
}

let handleCurrentChange = (page: number) => {
  getTrademark(page)
}

let handleSizeChange = () => {
  getTrademark()
}

let addTrades = () => {
  addTradesParames.id = 0
  addTradesParames.logoUrl = null
  addTradesParames.tmName = ''
  dialogVisible.value = true
}

onMounted(() => {
  getTrademark()
})

const handleAvatarSuccess = (response: any) => {
  console.log(123456, JSON.stringify(response))
  if (response.code === 200) {
    addTradesParames.logoUrl = response.data
  }
}

const beforeAvatarUpload = (file: any) => {
  // 上传之前的钩子
  // 限制文件类型  及大小  确保上传的是合适的  且是图片
  // 要求:上传文件格式png|jpg|gif 4M
  if (
    file.type === 'image/jpeg' ||
    file.type === 'image/png' ||
    file.type === 'image/gif'
  ) {
    if (file.size / 1024 / 1024 < 4) {
      return true
    } else {
      ElMessage({
        type: 'error',
        message: '上传图片大小需小于 4 M',
      })
      return false
    }
  } else {
    ElMessage({
      type: 'error',
      message: '上传图片类型需为 png/jpeg/gif 类型',
    })
    return false
  }
}
</script>

<style lang="scss">
.box-card {
  width: 100%;
  height: 100%;

  .tradeTable {
    margin: 15px 0;
  }
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
